<template>
  <el-container class="main_con">
    <ufrom @submit="saveData" ref="ufrom">
      <el-form size="medium" label-width="100px" ref="shForm" :model="obj" :rules="itemRules" class="edit_form">
        <div class="setting_body_item">
          <div class="header">{{ pageName }}</div>
          <div class="conetnt edit_con">
            <div class="edit_content">
              <el-form-item label="门店名称" prop="name"><el-input style="width:360px" placeholder="请输入门店名称" v-model="obj.name"></el-input></el-form-item>

              <el-form-item label="联系号码" prop="mobile"><el-input style="width:360px" placeholder="请输入手机号" v-model="obj.mobile"></el-input></el-form-item>

              <!-- <el-form-item label="所在区域" prop="districtSelected">
            <el-cascader
              :options="options"
              v-model="obj.districtSelected"
              @change="districtSelect"
              @visible-change="validateDistrict"
              ref="location"
              style="width:100%">
            </el-cascader>
          </el-form-item> -->

              <el-form-item label="所在区域" prop="districtSelected">
                <el-cascader style="width:360px" :options="options" v-model="obj.districtSelected" @change="districtSelect" ref="location" ></el-cascader>
              </el-form-item>

              <el-form-item label="地址" prop="address"><el-input style="width:360px"placeholder="请输入具体地址" v-model="obj.address"></el-input></el-form-item>

              <el-form-item label="门店位置" prop="longitude">
               <el-input placeholder="请输入经度" style="width:175px" v-model="obj.longitude"></el-input>

               <el-input class="u-m-l-10" placeholder="请输入纬度"  style="width:175px" v-model="obj.latitude"></el-input>
               <el-button class="ml_15" @click="showMap = true">获取坐标</el-button>
              </el-form-item>

              <el-form-item label="备注"><el-input style="width:360px" placeholder="请输入备注内容" v-model="obj.remark"></el-input></el-form-item>

              <!-- <el-form-item label="营业执照" prop="business_license">
            <Upload :tempUrl="obj.business_license" @input="getImage"></Upload>
          </el-form-item> -->

              <!-- <el-form-item label="状态">
            <el-radio-group v-model="obj.status">
              <el-radio :label="0">未启用</el-radio>
              <el-radio :label="1">正常</el-radio>
              <el-radio :label="2">禁用</el-radio>
            </el-radio-group>
          </el-form-item> -->
            </div>
          </div>
        </div>
      </el-form>
    </ufrom>

    <el-dialog title="选取坐标" :visible.sync="showMap" custom-class="maps" width="70%"><AMap @submitClose="closeMap" :pos="pos"></AMap></el-dialog>
  </el-container>
</template>

<script>
// import Upload from '@/components/Upload/SingleImage';
import AMap from '@/components/AMap/index';
import {regionData, CodeToText, TextToCode} from 'element-china-area-data';
import {addStore, editStore, getStore} from '@/api/shop/store';
export default {
  data() {
    //校验手机号码
    let validateMobile = (rule, value, callback) => {
      if (!/^1[23456789]\d{9}$/.test(value)) {
        callback(new Error('手机号码有误，请重填'));
      } else {
        callback();
      }
    };
    //校验区域
    // let validateDistrict = (rule, value,callback) => {
    //   if(value.length == 0){
    //     callback(new Error('请选择区域'));
    //   }
    // };

    //校验经纬度
    let validateLocation = (rule, value, callback) => {
      if (value == '') {
        callback(new Error('经纬度不能为空'));
      } else if (this.obj.latitude == '') {
        callback(new Error('经纬度不能为空'));
      } else {
        callback();
      }
    };

    //校验有效期
    let validateInDate = (rule, value, callback) => {
      if (!this.indate) {
        //没选中永久有效
        if (value == '') {
          callback(new Error('有效期不能为空'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };

    return {
      showMap: false,
      obj: {
        name: '',
        mobile: '',
        district: '',
        districtSelected: [],
        address: '',
        longitude: '',
        latitude: '',
        remark: '',
        status: 1
      },
      _obj: {},
      pageIsEdit: 0, //0->新增,1->编辑
      pageName: '新增门店',
      indate: false,
      isLoading: false,
      options: regionData,
      itemRules: {
        mobile: [
          {
            required: true,
            trigger: 'blur',
            validator: validateMobile
          }
        ],
        name: [
          {
            required: true,
            trigger: 'blur',
            message: '请输入门店名称'
          }
        ],
        longitude: [
          {
            required: true,
            //trigger: 'blur',
            validator: validateLocation
          }
        ],
        address: [
          {
            required: true,
            trigger: 'blur',
            message: '请输入具体地址'
          }
        ],
        districtSelected: [
          {
            type: 'array',
            required: true,
            //trigger: 'change',
            message: '请选择所在区域'
          }
        ]
        // business_license: [{
        //   required: true,
        //   trigger: 'change',
        //   message:'营业执照不能为空'
        // }],
      },
      pos: [120.683311, 28.007002]
    };
  },
  components: {
    AMap
  },
  created() {
    //console.log(this.$route.query.id)
    //获取路由参数(编辑时使用)
    if (this.$route.query.id) {
      //编辑页面
      this.pageIsEdit = 1;
      this.pageName = '编辑门店';
      this.getStoreData(this.$route.query.id);
    } else {
      this.pageIsEdit = 0;
      this.pageName = '新增门店';
      this._obj = Object.assign({}, this.obj);
    }
  },
  methods: {
    //获取编辑页面基础数据
    getStoreData(id) {
      this.isLoading = true;
      getStore(id).then(res => {
        this.isLoading = false;
        let o = res.msg;
        //this.obj = o;

        //处理所在区域
        let _d = [];
        let _t;
        if (o.district.indexOf(',') > -1) {
          _t = o.district.split(',');
        } else {
          _t = o.district.split(' ');
        }
        //拼接所在区域选择数组
        _d[0] = TextToCode[_t[0]].code;
        _d[1] = TextToCode[_t[0]][_t[1]].code;
        _d[2] = TextToCode[_t[0]][_t[1]][_t[2]].code;
        o.districtSelected = _d;

        //处理商户状态
        // switch(o.status){
        //   case '未启用':
        //     o.status = 0;
        //     break;
        //   case '正常':
        //     o.status = 1;
        //     break;
        //   case '禁用':
        //     o.status = 2;
        //     break;
        //   default:
        //     //no code
        //     break;
        // };

        //处理是否永久有效
        if (o.indate == 0) {
          this.indate = true;
        } else {
          this.indate = false;
        }
        this.pos = [o.longitude, o.latitude];
        //赋值
        this.obj = Object.assign({}, o);
      });
    },
    //获取图片
    getImage(val) {
      this.obj.business_license = val;
    },
    //级联选择区域
    districtSelect(value) {
      let s = '';
      value.forEach(e => {
        s += CodeToText[e] + ',';
      });
      s = s.substring(0, s.length - 1);
      //对象赋值
      this.obj.district = s;
    },
    //手动侦听事件触发校验
    validateDistrict(e) {
      //console.log(this.$refs.shForm)
      //this.$refs.shForm.validateField('districtSelected');
    },
    //保存数据
    saveData() {
      let that = this;
      let _data = Object.assign({}, this.obj);
      this.$refs.shForm.validate(valid => {
        if (valid) {
          //处理数据
          if (that.indate) {
            _data.indate = '0';
          }

          //delete _data.apply_id;
          //delete _data.update_time;

          //删除所在无用字段
          delete _data.districtSelected;

          //保存数据
          this.isLoading = true;
          switch (this.pageIsEdit) {
            case 0:
              //新增
              addStore(_data)
                .then(res => {
                  this.$refs.ufrom.init();
                  this.$router.push({path: '/store/storeList'});
                  // this.$refs.shForm.resetFields();
                  // this.obj = Object.assign({},this._obj);
                })
                .catch(e => {
                  this.$refs.ufrom.init();
                });
              break;
            case 1:
              //编辑
              //删除字段
              delete _data.status_text;
              editStore(_data)
                .then(res => {
                  this.$refs.ufrom.init();
                  this.$router.push({path: '/store/storeList'});
                  // this.getStoreData(this.$route.query.id);
                })
                .catch(e => {
                  this.$refs.ufrom.init();
                });
              break;
            default:
              //no code
              break;
          }
        } else {
          this.$refs.ufrom.init();
          return false;
        }
      });
    },
    //关闭坐标选择器窗口
    closeMap(e) {
      this.showMap = false;
      this.obj.longitude = e[0];
      this.obj.latitude = e[1];
    }
  }
};
</script>

<style lang="scss">
.my-autocomplete {
  li {
    line-height: normal;
    padding: 7px;

    .name {
      text-overflow: ellipsis;
      overflow: hidden;
    }
    .addr {
      font-size: 12px;
      color: #b4b4b4;
    }

    .highlighted .addr {
      color: #ddd;
    }
  }
}
</style>
